Logout

Home Topic 4 Last Next

Collections as Parameters and/or Return Values


This is the same program as before, only instead of the lists being global, they are declared inside the main method. But that means they need to be sent as arguments to the other method, where they are received as parameters.

But that's fine, arrays and lists and other structures can be sent as arguments, the same as primitive types like int and boolean.

1    public class ChillyAndHotWithParameters {
2    
3    
4        public static void main(String[] args) {
5            OurList<Integer> chillyList = new OurList<Integer>(); //now no longer global
6            OurList<Integer> hotList = new OurList<Integer>(); //so will need to be sent to other method
7            int [] allTemps = new int[365];
8            chillyList.resetNext();
9            hotList.resetNext();
10           for(int i = 0; i < allTemps.length; i++){
11               allTemps[i] = (int)(Math.random() * 24 + 16);
12               if(allTemps[i] < 20){
13                   chillyList.addItem(allTemps[i]);
14               }
15               else if(allTemps[i] > 37){
16                   hotList.addItem(allTemps[i]);
17               }
18           }
19           printOutLists(chillyList, hotList); //arguments sent
20       }
21   
22       public static void printOutLists(OurList<Integer> chillyTemps, OurList<Integer>hotTemps){
23                                         //parameters received
24           chillyTemps.resetNext();
25           if(!chillyTemps.isEmpty()){
26               while(chillyTemps.hasNext()){
27                   System.out.println("Next chilly temp. is " + chillyTemps.getNext());
28               }
29           }else{
30               System.out.println("Great, no chilly temps. at all!");
31           }
32   
33           hotTemps.resetNext();
34           if(!hotTemps.isEmpty()){
35               while(hotTemps.hasNext()){
36                   System.out.println("Next hot temp. is " + hotTemps.getNext());
37               }
38           }else{
39               System.out.println("Phewww... no temps. over 37 degrees.");
40           }
41       }
42   }